package simple.utils.concurrent;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by rehak on 4/8/14.
 */
public class NamedReentrantLock {

    private final ConcurrentMap<Object, ReentrantLock> locks = new ConcurrentHashMap<>();
    private final boolean fair;

    public NamedReentrantLock(boolean fair) {
        this.fair = fair;
    }

    public NamedReentrantLock() {
        this(false);
    }

    public void lock(Object name) {
        ReentrantLock lock = locks.get(name);
        if (lock == null) {
            lock = new ReentrantLock(fair);
            ReentrantLock oldLock = locks.putIfAbsent(name, lock);
            if (oldLock != null) {
                lock = oldLock;
            }
        }
        lock.lock();
    }

    public void unlock(Object name) {
        ReentrantLock lock = locks.get(name);
        if (lock != null) {
            lock.unlock();
        }
        locks.remove(name);
    }

}
